package components
{

import flash.events.KeyboardEvent;
import flash.system.System;
import flash.ui.Keyboard;

import mx.controls.AdvancedDataGrid;
import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;

/**
 *
 * ClipDataGrid : A derived class of AdvancedDataGrid that enables copying of data to the browser
 * clipboard.  This allows data to be copied to external applications such as MS Excel.
 *
 * @see mx.controls.AdvancedDataGrid
 */
public class ClipDataGrid extends AdvancedDataGrid
{
    /**
     * Constructor
     */
    function ClipDataGrid()
    {
        super();

        // Need to be able to select multiple cells
        allowMultipleSelection = true;
        selectionMode = "multipleCells";

        // Listen to keyboard events. We are looking for keyboard shortcuts.
        addEventListener(KeyboardEvent.KEY_UP,
                            keyboardShortcutHandler);
    }

    /**
     * Handle keyboard shortcuts.
     */
    private function keyboardShortcutHandler(event:KeyboardEvent):void
    {
        // If user pressed Ctrl-C
        var keycode_c:uint = 67;
        if (event.ctrlKey && event.keyCode == keycode_c)
        {
            // Separator used in string-sent-to-clipboard to separate columns in the tabular data
            var separator:String = ",";
            // The string-sent-to-clipboard
            var dataString:String = "";

            // Loop over the selectedCells
            // Note that selectedCells is ordered such that the latest is at
            // the head of the list, so we'll have to process it in reverse so
            // that we can set the clipboard correctly.
            var n:int = selectedCells.length;
            for (var i:int = 0; i < n; i++)
            {
                var cell:Object = selectedCells[i];
                var data:Object = dataProvider[cell.rowIndex];
                var dataField:String = columns[cell.columnIndex].dataField;
                dataString = data[dataField] + separator + dataString;
            }

            // Remove trailing separator
            dataString = dataString.substr(0, dataString.length - separator.length);

            // Now, dataString, the string-sent-to-clipboard contais a tabular plain text
            // representation of the selected rows in the DataGrid, in the order they were selected.
            // So, copy to the clipboard.
            System.setClipboard(dataString);
        }
    }
}

}
